package com.dc.es.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.cat.IndicesRequest;
import co.elastic.clients.elasticsearch.cat.IndicesResponse;
import co.elastic.clients.elasticsearch.cat.indices.IndicesRecord;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/es")
@Slf4j
public class EsController {


    private final ElasticsearchClient elasticsearchClient;

    public EsController(ElasticsearchClient elasticsearchClient) {
        this.elasticsearchClient = elasticsearchClient;
    }


    @GetMapping("/test")
    public String esTest() throws IOException {
        BooleanResponse ping = elasticsearchClient.ping();
        log.info("esTest={}",JSONObject.toJSONString(ping));
        return JSONObject.toJSONString(ping.value());
    }

    @GetMapping("/data")
    public String  esData() throws IOException {

        // 构建 Cat Indices 请求
        IndicesRequest request = IndicesRequest.of(r -> r);

        // 发送请求并获取响应
        IndicesResponse response = elasticsearchClient.cat().indices(request);
        // 打印索引信息
        response.valueBody().forEach(index -> {
            System.out.println("Index Name: " + index.index());
            System.out.println("Index Status: " + index.status());
            System.out.println("Index Health: " + index.health());
            System.out.println("Index Total Docs: " + index.docsCount());
            System.out.println("Index Store Size: " + index.storeSize());
            System.out.println();
        });
        System.out.println("response.valueBody()=" + response.valueBody());
        List<IndicesRecord> indicesRecords = response.valueBody();
        return  indicesRecords.toString();
    }
}
